﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace YmSoft.Old
{
    /// <summary>
    /// ProtocolItemFactory
    /// </summary>
    public static class MsgFactory
    {
        static Dictionary<Type, MsgAttribute> dict;
        static MsgFactory()
        {
            dict = new Dictionary<Type, MsgAttribute>();
            Assembly.GetCallingAssembly()
                .GetTypes()
                .Where(p => p.GetCustomAttributes(typeof(MsgAttribute), true).Length > 0)
                .ToList()
                .ForEach(type =>
                    {
                        dict[type] = type.GetCustomAttributes(typeof(MsgAttribute), true).First() as MsgAttribute;
                    });


        }

        internal static MsgAttribute GetMsgAttribute(Type type)
        {
            return dict[type];
        }

        public static MsgBase GetMsg(byte[] data)
        {
            var kvs = dict.Where(p => p.Value.Check(data));
            if (kvs.Count() == 0)
            {
                return null;
            }
            var kv = kvs.First();
            return Activator.CreateInstance(kv.Key, data) as MsgBase;
        }

        public static byte[] GetEmptyMsgData(Type type)
        {
            var att = GetMsgAttribute(type);
            var result = new byte[att.帧长];
            result[0] = att.帧头;
            result[1] = att.帧长;
            result[att.帧长 - 1] = att.检验字节;
            return result;
        }
    }
}
